
let Socket = ''
let setIntervalWesocketPush = null
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = url => {
  Socket && Socket.close()
  if (!Socket) {
    console.log('建立websocket连接')
    Socket = new WebSocket(url)
    Socket.onopen = onopenWS
    Socket.onmessage = onmessageWS
    Socket.onerror = onerrorWS
    Socket.onclose = oncloseWS
  } else {
    console.log('websocket已连接')
  }
}

/**打开WS之后发送心跳 */
export const onopenWS = () => {
  console.log('websocket已连接')
  sendPing()
}

/**连接失败重连 */
export const onerrorWS = () => {
  Socket.close()
  console.log('连接失败重连中')
  if (Socket.readyState !== 3) {
    Socket = null
    createSocket()
  }
}

/**WS数据接收统一处理 */
export const onmessageWS = e => {
  if (e.data) {
    try {
      let obj = JSON.parse(e.data)
      if (obj) {
          window.dispatchEvent(new CustomEvent('onmessageWS', {
            detail: {
              data: obj
            }
          }))
      }
    } catch (error) {
      
    }
  }
}

/**断开连接 */
export const oncloseWS = () => {
  console.log('websocket已断开....')
  Socket && Socket.close()
  Socket = null
}


/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 5000, ping = 'ping') => {
  clearInterval(setIntervalWesocketPush)
  Socket.send(ping)
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(ping)
  }, time)
}